package photobox

import grails.converters.JSON
import groovy.xml.MarkupBuilder
import javassist.runtime.Desc
import photobox.account.Member
import photobox.account.Region
import photobox.manage.OrderService
import photobox.order.Order
import photobox.order.OrderItem
import photobox.photo.Photo
import photobox.photo.PhotoFrame
import photobox.photo.PhotoFramePrice
import photobox.photo.PhotoPaper
import photobox.photo.PhotoPaperPrice
import photobox.photo.PhotoSize

import com.alipay.config.*
import com.alipay.util.*

import java.text.SimpleDateFormat
import  java.util.HashMap
import java.util.Map

class OrderController extends BaseController {
    def orderService
    def memberService
    def index() {}

    def saveAddress(){
        if(session.userId){
            println(params)
            def r = memberService.saveAddress(params, session.userId)
            if(r){
                render ([status:1] as JSON)
            }else{
                render ([status:0, msg:'更新失败'] as JSON)
            }
        }else{
            render ([status:0, msg:'请重新登录'] as JSON)
        }
    }

    def saveOrder(){
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }
        def o = orderService.saveOrder(params, session)
        if(o){
            orderService.sendMessage(session.userId,"提交订单成功！ 订单号为："+o.id)
            Date currentTime = new Date(o.dateCreated.time)
            SimpleDateFormat formatter = new SimpleDateFormat("HHmmss")
            String dateString = formatter.format(currentTime)
            session.removeAttribute("orderItems")
            redirect(action:"alipaySubmit", params:[orderId:dateString +o.id,totalPrice:0.01])
        }else{
            render('提交订单失败')
        }
    }
    def proceedPay(){
        def orderId = params.orderId
        def o =Order.get(orderId)
        Date currentTime = new Date(o.dateCreated.time);
        SimpleDateFormat formatter = new SimpleDateFormat("HHmmss");
        String dateString = formatter.format(currentTime);
        redirect(action:"alipaySubmit", params:[orderId:dateString + orderId,totalPrice:0.01])
    }
    def receiveConfirmation(){
        orderService.updateOrderStatus(params.orderId,Order.ORDER_STATUS_RECEIVED)
        redirect(action:"order")
    }
    def shoppingCart(){
        /*
        Float  framePrice       //相框价格
        Float  paperPrice       //纸张价格
        Float  photoPrice       //图片价格
        Float  packingPrice     //包装价格
         */
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }else {
            def yunPrice=10
            def photoFrame = PhotoFrame.get(params.photoFrame)
            def photoSize = PhotoSize.get(params.photoSize)
            def photoPaper = PhotoPaper.get(params.photoPaper)
            def framePrice = PhotoFramePrice.findByPhotoFrameAndPhotoSize(photoFrame,photoSize).price
            def paperPrice = PhotoPaperPrice.findByPhotoPaperAndPhotoSize(photoPaper,photoSize).price
            def packingPrice = photoSize.packingPrice
            def price = Photo.get(params.photoId).price
            def eachPrice = Photo.get(params.photoId).price + framePrice + paperPrice + packingPrice
            def totalPrice = Photo.get(params.photoId).price + framePrice + paperPrice + packingPrice+yunPrice
            Map orderItem = [ photoId:params.photoId,price:price, photoPaper:params.photoPaper, photoFrame:params.photoFrame ,photoSize:params.photoSize,framePrice:framePrice,paperPrice:paperPrice,packingPrice:packingPrice,number:1,eachPrice:eachPrice,totalPrice:totalPrice]

            if(!session.orderItems){
                orderItem.itemId = 0
                session.orderItems = [orderItem]
            }else {
                def len = session.orderItems.size()
                def lastItem = session.orderItems[len -1]
                def itemId = lastItem.itemId
                orderItem.itemId = itemId + 1
                def flag =true
                if(params.photoId == lastItem.photoId && params.photoSize == lastItem.photoSize && params.photoPaper == lastItem.photoPaper && params.photoFrame == lastItem.photoFrame){
                    flag = false
                }
                if(flag == true){
                    session.orderItems.add(orderItem)
                }
                totalPrice = 0
                for (int i = 0; i < session.orderItems.size(); i++) {

                    session.orderItems[i].eachPrice = session.orderItems[i].number * (session.orderItems[i].price + session.orderItems[i].framePrice + session.orderItems[i].paperPrice + session.orderItems[i].packingPrice)

                    totalPrice = totalPrice + session.orderItems[i].eachPrice+session.orderItems[i].number * yunPrice
                   // session.orderItems[i].totalPrice = 0
                    if(i>0){//防止订单页面刷新时价格出错
                        session.orderItems[i].totalPrice = totalPrice-session.orderItems[i-1].totalPrice
                    }else{
                        session.orderItems[i].totalPrice = totalPrice
                    }

                }
            }

            if(params.json){
                render ([shoppingCartNum:session.orderItems.size()] as JSON)
            }else{
                [orderItems:session.orderItems,totalPrice:totalPrice]
            }
        }
    }
    def buy(){
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }
        def hql = "select S from Photo as P join P.photoSize as S where P.id = :photoId"
        def photo = Photo.get(params.id)
        def photoFrameList = PhotoFrame.findAll()
        def photoPaperList = PhotoPaper.findAll()
        def photoSizeList = Photo.executeQuery(hql, ['photoId': photo.id])

        def sellPhoto = OrderItem.executeQuery("from OrderItem as I where I.photo=:photo",[photo:photo],[max:1])
        def photoOwner = []
        if(sellPhoto != []) {
            def otherPhoto = Order.executeQuery("from Order as O where O.orderStatus>=20 and  O.user=:user",[user:sellPhoto.order.user])
            def photos = []
            otherPhoto.each {
                it.items.each {
                    photos = []
                    photos.push(it.photo)
                    if(photos != sellPhoto.photo && photoOwner.size()<3) {
                        photoOwner.push(it.photo)
                    }
                }
            }
        }
        def photoNum = Photo.countByUser(photo.user)
        //作品主题风格
        def theme = []
        def style = []
        photo.categories.each {
            if(it.categoryType == 1) {
                theme.push([name:it.name,id:it.id])
            }else if(it.categoryType == 2) {
                style.push([name:it.name,id:it.id])
            }
        }
        [photo:photo,photoFrameList:photoFrameList,photoPaperList:photoPaperList,photoSizeList:photoSizeList,photoOwner:photoOwner,photoNum:photoNum,theme:theme,style:style]

    }

    def buyAddress(){
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }else {
            def member = Member.get(session.userId)
            def cityList = new Region()
            def districtList = new Region()
            def provinceList = Region.findAllByRegionLevel(2)

            if (member.address?.size() == 0) {
                cityList = null
                districtList = null
            } else {
                cityList = Region.findAllByPid(member.address[0].province.id)
                districtList = Region.findAllByPid(member.address[0].city.id)
            }


            //是否开发票
            def isInvoiceData = [
                    [id:Order.IS_INVOICE_NO,text:'否'],
                    [id:Order.IS_INVOICE_YES,text:'是']
            ]
            //发票类型
            def invoiceTypeData = [
                    [id:Order.INVOICE_TYPE_PERSONAL,text:'个人'],
                    [id:Order.INVOICE_TYPE_ORGANIZATION,text:'单位']
            ]
            //发票种类
            def invoiceSortData = [
                    [id:Order.INVOICE_SORT_TRAFFIC,text:'交通'],
                    [id:Order.INVOICE_SORT_BOOK,text:'书']
            ]
            def photo = Photo.get(session.orderItems?.photoId)
            [photo:photo,user:member,provinceList: provinceList, cityList: cityList, districtList: districtList,isInvoiceData:isInvoiceData,
             invoiceTypeData:invoiceTypeData, invoiceSortData:invoiceSortData]
        }

    }
    def points(){
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }
    }
    def order(){
        if(params.json){
            def max = params.max
            def offset = params.offset
            if(session.userId == null){
                return 
            }
            def member = Member.get(session.userId)
            //def orders = Order.findAllByUser(member, [max:max, offset:offset])
            //def hql = 'from Order o where o.user=:member order by o.dateCreated desc'
            def hql = ' from Order as O join O.items as OI where O.user=:member order by O.dateCreated desc'
            def orders = Photo.executeQuery(hql,[member:member],[max:max, offset:offset])
            def order = []
            def orderList =[]
            orders.each {
                if(!(it[0] in orderList)) {
                    orderList.push(it[0])
                    order.push(
                            dateCreated:it[0].dateCreated,
                            id:it[0].id,
                            photoName:it[1].photo.name,
                            totalPrice:it[0].totalPrice,
                            orderStatus:it[0].orderStatus,
                    )
                }
            }
            def o = max.toInteger() +  offset.toInteger()
            render ([orders:order, offset: o,max:max] as JSON)
        }
    }

    def alipaySubmit(){
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }
        String path = request.getContextPath()
        String domain_name = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"
        ////////////////////////////////////请求参数//////////////////////////////////////

        //支付类型
        String payment_type = "1";
        //必填，不能修改
        //服务器异步通知页面路径
        String notify_url = domain_name +"order/payNotifyUrl";
        //需http://格式的完整路径，不能加?id=123这类自定义参数		//页面跳转同步通知页面路径
        String return_url = domain_name +"order/payReturnUrl";
        //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/		//卖家支付宝帐户
        String seller_email = AlipayConfig.seller_email;;
        //必填		//商户订单号
        //Calendar now = Calendar.getInstance();
        //def orderNumber = now.getTimeInMillis()
        String out_trade_no = params.orderId;
        //商户网站订单系统中唯一订单号，必填		//订单名称
        String subject = 'photobox订单';
        //必填		//付款金额
        String total_fee =  params.totalPrice;
        //必填		//订单描述
        String body = 'photobox订单描述';
        //商品展示地址
        String show_url = domain_name;
        //需以http://开头的完整路径，例如：http://www.商户网址.com/myorder.html
        // 防钓鱼时间戳
        String anti_phishing_key = "";
        //若要使用请调用类文件submit中的query_timestamp函数		//客户端的IP地址
        String exter_invoke_ip = "";
        //非局域网的外网IP地址，如：221.0.0.1
        //帐号 uniwin@uustock.com

        String service = "create_direct_pay_by_user";
        String partner = AlipayConfig.partner;
        String _input_charset = AlipayConfig.input_charset;
        String sign_type = AlipayConfig.sign_type;
        Map<String, String> sParaTemp = new HashMap<String, String>();
        sParaTemp.put("service", "create_direct_pay_by_user");
        sParaTemp.put("partner", AlipayConfig.partner);
        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
        sParaTemp.put("payment_type", payment_type);
        sParaTemp.put("notify_url", notify_url);
        sParaTemp.put("return_url", return_url);
        sParaTemp.put("seller_email", seller_email);
        sParaTemp.put("out_trade_no", out_trade_no);
        sParaTemp.put("subject", subject);
        sParaTemp.put("total_fee", total_fee);
        sParaTemp.put("body", body);
        sParaTemp.put("show_url", show_url);
        String sign = AlipaySubmit.getSign(sParaTemp);

        //////////////////////////////////////////////////////////////////////////////////
        [service:service, partner:partner, _input_charset:_input_charset, payment_type:payment_type, notify_url:notify_url, return_url:return_url, seller_email:seller_email,
         out_trade_no:out_trade_no, subject:subject, total_fee:total_fee, body:body, show_url:show_url, sign_type:sign_type, sign:sign]

    }
    def orderItems(){
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }

        def order = Order.get(params.orderId)
        def user = Member.get(order.user.id)
        if(params.json =='1') {
            if(orderService.updateOrderStatus(params.orderId,Order.ORDER_STATUS_RECEIVED)){
                render([status: 1] as JSON)
            }else{
                render([status: 0] as JSON)
            }
        }
        [order:order,user:user]
    }
    def orderItemsChange(){
        def i = ''
        def orderItems = ''
        def yunPrice = 10        //运费
        session.orderItems.eachWithIndex{item,n ->
            if(Integer.parseInt(params.itemId) == item.itemId){
                i = n
                orderItems = item
            }
        }
       // def orderItems = session.orderItems[Integer.parseInt(params.i)]
        //println(orderItems)
        //println(params)
        if(params.type=="add"){
            orderItems.number +=1
            yunPrice = orderItems.number * yunPrice
            def eachPrice = orderItems.number *(orderItems.price + orderItems.framePrice +orderItems.paperPrice+orderItems.packingPrice)       //照片价格
            def TPrice = orderItems.number *(orderItems.price + orderItems.framePrice +orderItems.paperPrice+orderItems.packingPrice)+yunPrice // 小计=运费+照片价格
            render ([number:orderItems.number,tprice:eachPrice,price:orderItems.price + orderItems.framePrice +orderItems.paperPrice+orderItems.packingPrice,TPrice:TPrice,yunPrice:yunPrice] as JSON)


        }else if(params.type=="diminish"){
            if(orderItems.number>=2){
                orderItems.number -=1
                yunPrice = orderItems.number * yunPrice
                def eachPrice = orderItems.number *(orderItems.price + orderItems.framePrice +orderItems.paperPrice+orderItems.packingPrice)
                def TPrice = orderItems.number *(orderItems.price + orderItems.framePrice +orderItems.paperPrice+orderItems.packingPrice)+yunPrice // 小计=运费+照片价格
                render ([number:orderItems.number,tprice:eachPrice,price: orderItems.price + orderItems.framePrice +orderItems.paperPrice+orderItems.packingPrice,TPrice:TPrice,yunPrice:yunPrice] as JSON)
            }
        }else if(params.type=="del"){
            def eachPrice = orderItems.eachPrice
            session.orderItems.remove(i)
            render ([tprice:eachPrice] as JSON)
        }
    }
    def clearCart(){

        def isClear = "isClear"
        session.orderItems=[]
        render ([isClear:isClear,len:session.orderItems.size()] as JSON)
        //println(session.orderItems)
    }
    def payNotifyUrl(){
        /*
           File f = new File("alipaytest.txt");
           if (!f.exists()) {
               f.createNewFile();
           }
           FileWriter writer = new FileWriter("alipaytest.txt");
writer.write(out_trade_no +'-------'+out_trade_no.substring(6)+'-----'+Order.ORDER_STATUS_PAID.toString());
        writer.close();

      [buyer_id:2088702880694914, trade_no:2014111831415691, body:在哪里, use_coupon:N, notify_time:2014-11-18 15:07:27, subject:厅要, sign_type:MD5, is_total_fee_adjust:N,
       notify_type:trade_status_sync, out_trade_no:1416294351064, gmt_payment:2014-11-18 15:07:27, trade_status:TRADE_SUCCESS, discount:0.00, sign:b518ebaa8e81307a078a059a6cf97839,
       buyer_email:18910789485, gmt_create:2014-11-18 15:06:59, price:0.01, total_fee:0.01, quantity:1, seller_id:2088601079283763,
       notify_id:41bf663ea0e6181eed7bf920282af87c72, seller_email:uniwin@uustock.com, payment_type:1, action:payNotifyUrl, format:null, controller:order]
       */
        //获取支付宝POST过来反馈信息
        Map<String,String> params2 = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params2.put(name, valueStr);
        }

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");


        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

        if(AlipayNotify.verify(params2)){//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码

            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //该种交易状态只在两种情况下出现
                //1、开通了普通即时到账，买家付款成功后。
                //2、开通了高级即时到账，从该笔交易成功时间算起，过了签约时的可退款时限（如：三个月以内可退款、一年以内可退款等）后。
            } else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //该种交易状态只在一种情况下出现——开通了高级即时到账，买家付款成功后。
                def orderId = out_trade_no.substring(6)
                def order = Order.get(orderId);
                if(order.orderStatus == Order.ORDER_STATUS_COMMIT) {//10
                    orderService.updatePhotoSaleNum(orderId)
                    def r = orderService.updateOrderStatus(orderId, Order.ORDER_STATUS_PAID)
                    orderService.sendMessage(order.userId, '支付成功，订单号为 ' + orderId + ', 支付宝交易号为 ' + trade_no);
                }
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

            println("success");	//请不要修改或删除

            //////////////////////////////////////////////////////////////////////////////////////////
        }else{//验证失败
            println("fail");
        }
    }
    def payReturnUrl(){
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

        //计算得出通知验证结果
        boolean verify_result = AlipayNotify.verify(params);
        if(verify_result){//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码

            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                redirect(action:"paySuccess", params:[out_trade_no:out_trade_no])
            }

            //该页面可做页面美工编辑
            println("验证成功<br />");
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

            //////////////////////////////////////////////////////////////////////////////////////////
        }else{
            //该页面可做页面美工编辑
            println("验证失败");
        }

    }
    def showPhotoFrame(){
        def photoFrame = PhotoFrame.get(params.photoFrame)
        def description = photoFrame.description
        render ([descriptions:description] as JSON)
    }
    def paySuccess(){
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }
    }
}
